package com.atguigu.exam.service.impl;

import com.atguigu.exam.config.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file, String foler) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {


        //判断是否有桶
        boolean bucketedExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        //没有则进行创建
        if (!bucketedExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            //定义权限
            String policy= """
                    {
                                "Statement" : [ {
                                "Action" : "s3:GetObject",
                                "Effect" : "Allow",
                                "Principal" : "*",
                                "Resource" : "arn:aws:s3:::%s/*"
                                } ],
                                "Version" : "2012-10-17"
                                            }
                    """.formatted(minioProperties.getBucketName());
            //设置权限
            minioClient.setBucketPolicy(SetBucketPolicyArgs.
                    builder()
                            .bucket(minioProperties.getBucketName())
                            .config(policy)
                    .build());
        }
        //定义文件名: 文件夹+文件名
        //生成一个uuid，uuid默认是带有-的，同时把-替换成""
        String uuid = UUID.randomUUID().toString().replace("-","");
        //整合对象名字
        String objectNmae=foler+"/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+uuid +file.getOriginalFilename();

        //上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .contentType(file.getContentType())//文件类型
                .object(objectNmae)
                //stream上传的数据流
                //参数1：要上传的文件的数据流
                //参数2:上传的文件的大小
                //参数3:是否切割文件，-1minio自动切割
                .stream(file.getInputStream(),file.getSize(),-1)
                .build());
        //拼接回显地址
        String url = minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+objectNmae;
        return url;
    }
}
